/**
 * 错误处理模块统一导出
 */

// 基础错误类
export { GameError } from './GameError';
export type { ClientSafeError, DetailedErrorInfo } from './GameError';

// 业务错误类
export * from './BagError';
export * from './RPGError';
export * from './TaskError';
export * from './SystemError';

// 错误处理中间件
// export { ErrorHandler } from '../api/middleware/ErrorHandler'; // 暂时注释掉，等API中间件就绪后启用

/**
 * 错误类型枚举
 */
export enum ErrorType {
    // 背包错误
    BAG_FULL = 'BAG_FULL',
    ITEM_NOT_FOUND = 'ITEM_NOT_FOUND',
    INSUFFICIENT_ITEM = 'INSUFFICIENT_ITEM',
    INVALID_ITEM_TYPE = 'INVALID_ITEM_TYPE',
    ITEM_USAGE_RESTRICTED = 'ITEM_USAGE_RESTRICTED',
    BAG_OPERATION_ERROR = 'BAG_OPERATION_ERROR',

    // RPG错误
    INSUFFICIENT_LEVEL = 'INSUFFICIENT_LEVEL',
    INVALID_EXP = 'INVALID_EXP',
    INSUFFICIENT_ATTRIBUTE_POINTS = 'INSUFFICIENT_ATTRIBUTE_POINTS',
    SKILL_LEARN_ERROR = 'SKILL_LEARN_ERROR',
    SKILL_USAGE_ERROR = 'SKILL_USAGE_ERROR',
    BATTLE_STATE_ERROR = 'BATTLE_STATE_ERROR',
    BLOODLINE_ERROR = 'BLOODLINE_ERROR',
    EQUIPMENT_ERROR = 'EQUIPMENT_ERROR',

    // 任务错误
    TASK_NOT_FOUND = 'TASK_NOT_FOUND',
    TASK_ALREADY_COMPLETED = 'TASK_ALREADY_COMPLETED',
    TASK_CONDITION_NOT_MET = 'TASK_CONDITION_NOT_MET',
    INVALID_TASK_PROGRESS = 'INVALID_TASK_PROGRESS',
    TASK_REWARD_CLAIM_ERROR = 'TASK_REWARD_CLAIM_ERROR',
    WORLD_TASK_ERROR = 'WORLD_TASK_ERROR',
    TASK_CONFIG_ERROR = 'TASK_CONFIG_ERROR',

    // 系统错误
    SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE',
    CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',
    DATABASE_ERROR = 'DATABASE_ERROR',
    NETWORK_ERROR = 'NETWORK_ERROR',
    AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR',
    AUTHORIZATION_ERROR = 'AUTHORIZATION_ERROR',
    VALIDATION_ERROR = 'VALIDATION_ERROR',
    BUSINESS_LOGIC_ERROR = 'BUSINESS_LOGIC_ERROR',
    INSUFFICIENT_RESOURCE = 'INSUFFICIENT_RESOURCE',
    OPERATION_TIMEOUT = 'OPERATION_TIMEOUT'
}

/**
 * 错误工厂类
 */
export class ErrorFactory {
    /**
     * 创建背包已满错误
     */
    static createBagFullError(currentSize?: number, maxSize?: number) {
        const { BagFullError } = require('./BagError');
        return new BagFullError(currentSize, maxSize);
    }

    /**
     * 创建物品不存在错误
     */
    static createItemNotFoundError(itemId: string, itemType?: string) {
        const { ItemNotFoundError } = require('./BagError');
        return new ItemNotFoundError(itemId, itemType);
    }

    /**
     * 创建等级不足错误
     */
    static createInsufficientLevelError(requiredLevel: number, currentLevel: number, action: string) {
        const { InsufficientLevelError } = require('./RPGError');
        return new InsufficientLevelError(requiredLevel, currentLevel, action);
    }

    /**
     * 创建任务不存在错误
     */
    static createTaskNotFoundError(taskId: string) {
        const { TaskNotFoundError } = require('./TaskError');
        return new TaskNotFoundError(taskId);
    }

    /**
     * 创建服务不可用错误
     */
    static createServiceUnavailableError(serviceName: string) {
        const { ServiceUnavailableError } = require('./SystemError');
        return new ServiceUnavailableError(serviceName);
    }
}

/**
 * 错误处理工具类
 */
export class ErrorUtils {
    /**
     * 检查是否为特定类型的游戏错误
     */
    static isErrorOfType(error: any, errorType: ErrorType): boolean {
        return error instanceof Error && error.constructor.name.includes(errorType);
    }

    /**
     * 从错误中提取错误码
     */
    static extractErrorCode(error: any): string {
        if (error && typeof error === 'object' && 'code' in error) {
            return error.code;
        }
        return 'UNKNOWN_ERROR';
    }

    /**
     * 格式化错误消息用于日志记录
     */
    static formatErrorForLogging(error: Error, context?: any): string {
        const timestamp = new Date().toISOString();
        const errorCode = this.extractErrorCode(error);
        
        return `[${timestamp}] Error[${errorCode}]: ${error.message}${
            context ? ` | Context: ${JSON.stringify(context)}` : ''
        }${error.stack ? ` | Stack: ${error.stack}` : ''}`;
    }

    /**
     * 创建错误摘要
     */
    static createErrorSummary(errors: Error[]): {
        total: number;
        byType: Record<string, number>;
        recent: Error[];
    } {
        const summary = {
            total: errors.length,
            byType: {} as Record<string, number>,
            recent: errors.slice(-5) // 最近的5个错误
        };

        errors.forEach(error => {
            const code = this.extractErrorCode(error);
            summary.byType[code] = (summary.byType[code] || 0) + 1;
        });

        return summary;
    }
}
